package com.frx.leetoffer.link;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/10/17
 * @Time: 11:21
 */
public class SwapLink {

    public static void main(String[] args){
        Node node = new Node(1);
        Node node2 = new Node(2,node);
        Node node3 = new Node(3,node2);
        Node node4 = new Node(4,node3);
        Node node5 = new Node(5,node4);
        printLink(node5);
        printLink(swapLink(node5));

    }



    public static Node swapLink(Node head){
        Node newNode = new Node(0);
        Node pre = newNode;
        Node cur = head;
        Node next = head.next;
        while (next!= null && next.next != null){
            Node temp = next.next;
            pre.next = next;
            next.next = cur;
            cur.next = temp;
            pre = cur;
            cur = temp;
            next = cur.next;
        }
        return newNode.next;
    }

    public static void printLink(Node head){
        System.out.print(head.val);
        head = head.next;
        while (head!=null){
            System.out.print(" -> " + head.val);
            head = head.next;
        }
        System.out.println();

    }
    public static Node swapPairs(Node head){
        if(head==null||head.next==null){
            return head;
        }
        Node next = head.next;
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }


    private static class Node{
        int val;
        Node next;
        Node(int val){
            this.val = val;
        }
        Node(int val,Node next){
            this.val = val;
            this.next = next;
        }

    }
}
